package cn.jinjimi.app.main.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.SparseArray;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFUserInfo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Iterator;
import java.util.List;

import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.AppManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.ShareProxy;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.Permissions;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.app.controller.event.LogoutEvent;
import cn.jinjimi.app.entity.AppConfig.AppTabBean;
import cn.jinjimi.app.entity.MainTab;
import cn.jinjimi.app.interfaces.IMainView;
import cn.jinjimi.app.main.extend.BaseActivity;
import cn.jinjimi.app.main.widget.ToolBar.CommonToolbar;
import cn.jinjimi.app.main.widget.ToolBar.ToolbarHelper;
import cn.jinjimi.app.managers.ConfigManager;
import cn.jinjimi.app.presenter.MainPresenter;
import cn.jinjimi.app.util.PreventContinuousClickUtil;
import cn.jinjimi.app.util.StatusbarUtils;
import cn.jinjimi.app.webview.bean.ShareAction;
import cn.jinjimi.app.webview.event.Route2CustomerService;
import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.util.ExitUtil;
import cn.jinjimi.framework.analy.AnalyManager;
import cn.jinjimi.framework.router.RouterHelper;

public class MainActivity extends BaseActivity implements IMainView, View.OnClickListener{

    private final int[] titles = new int[] {
            R.string.title_home,
            R.string.title_cate,
            R.string.title_vip,
            R.string.title_cert,
            R.string.title_me
    };

    private int[] tabIds = new int[]{
            R.id.btn_home,
            R.id.btn_cate,
            R.id.btn_vip,
            R.id.btn_cert,
            R.id.btn_me
    };

    private RadioGroup rgMainNav;
    private RadioButton mHomeRb;
    private RadioButton mCateRb;
    private RadioButton mVipRb;
    private RadioButton mCertRb;
    private RadioButton mMeRb;
    private LinearLayout llNetError;
    private int mIndexPagerPosition = 0;
    private int mCurSelectedTabId = -1;
    private SparseArray<Fragment> mTabFragment;
    private Fragment mLastFragment = null;
    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener;
    private ToolbarHelper mToolbarHelper;
    private MainPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (mTabFragment == null) {
            mTabFragment = new SparseArray<>();
        }
        mTabFragment.clear();
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StatusbarUtils.enableTranslucentStatusbar(this);
            StatusbarUtils.setLightTheme(this);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null && (mTabFragment == null || mTabFragment.size() == 0)) {
            resetState();
        }
        super.onPostCreate(savedInstanceState);
    }

    private void resetState() {
        try {
            Class cls = FragmentManager.class;
            List<Fragment> fragments = (List<Fragment>) cls.getMethod("getFragments").invoke(getSupportFragmentManager());
            if (fragments != null && fragments.size() > 0) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                Iterator<Fragment> it = fragments.iterator();
                while (it.hasNext()) {
                    Fragment fragment = it.next();
                    if (fragment != null) {
                        transaction.remove(fragment);
                    }
                }
                transaction.commitAllowingStateLoss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setContentView(int layoutResId) {
        mToolbarHelper = new ToolbarHelper(this, layoutResId);
        CommonToolbar toolbar = mToolbarHelper.createToolbar();
        toolbar.setOnClickListener(this);
        setContentView(mToolbarHelper.getContentVew());
        setSupportActionBar(toolbar);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] results) {
        super.onRequestPermissionsResult(requestCode, permissions, results);
        Permissions.onRequestPermissionsResult(this, requestCode, permissions, results);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mIndexPagerPosition = 0;
        try {
            if (intent.hasExtra(BundleKey.PARAM_MAIN_POSITION)) {
                String position = intent.getStringExtra(BundleKey.PARAM_MAIN_POSITION);
                mIndexPagerPosition = Integer.parseInt(position);
            } else if (intent.hasExtra(BundleKey.POSITION)) {
                String position = intent.getStringExtra(BundleKey.POSITION);
                mIndexPagerPosition = Integer.parseInt(position);
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        selectPager(mIndexPagerPosition);
    }

    @Override
    protected void beforeInitView() {
        setSwipeEnabled(false);
        Permissions.checkPermissions(this, Permissions.REQUEST_STORAGE_PERMISSIONS);
        ConfigManager.getInstance().hasMainActivityStarted(true);
        setContentView(R.layout.activity_tab);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        selectPagerForce(0);
    }

    protected void initView() {
        rgMainNav = (RadioGroup) findViewById(R.id.rg_main_nav);
        mHomeRb = (RadioButton) findViewById(R.id.btn_home);
        mCateRb = (RadioButton) findViewById(R.id.btn_cate);
        mVipRb = (RadioButton) findViewById(R.id.btn_vip);
        mMeRb = (RadioButton) findViewById(R.id.btn_me);
        mCertRb = (RadioButton) findViewById(R.id.btn_cert);
        mPresenter = new MainPresenter(this, this);
        llNetError = (LinearLayout) findViewById(R.id.ll_net_error);
    }

    int mPosition = 0;

    protected void initListener() {
        mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (!shouldShowLogin(getPosition(checkedId))) {
                    mPosition = getPosition(checkedId);
                    showTitle(mPosition);
                    showTabFragment(mPosition);
                } else {
                    selectPager(mPosition);
                }
            }
        };
        rgMainNav.setOnCheckedChangeListener(mOnCheckedChangeListener);
        llNetError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                return;
            }
        });
    }

    private int getPosition(int id) {
        switch (id) {
            case R.id.btn_home:
                return MainTab.MAIN.getPosition();
            case R.id.btn_cate:
                return MainTab.CATE.getPosition();
            case R.id.btn_vip:
                return MainTab.VIP.getPosition();
            case R.id.btn_me:
                return MainTab.ME.getPosition();
            case R.id.btn_cert:
                return MainTab.CERT.getPosition();
            default:
                return 0;
        }
    }

    private void showTitle(int position) {
        if (position == 0
            || position == 1) {
            mToolbarHelper.hideToolBar();
        } else if (position > 1 && position < titles.length) {
            mToolbarHelper.showToolBar();
            setTitle(titles[position]);
        }
    }

    private void showTabFragment(int position) {
        if (position > -1 && position < MainTab.values().length && mCurSelectedTabId != position) {
            if (mTabFragment == null) {
                mTabFragment = new SparseArray<>();
            }
            Fragment fragment = mTabFragment.get(position);
            if (fragment == null) {
                try {
                    MainTab tab = MainTab.values()[position];
                    fragment = (Fragment) tab.getClz().newInstance();

                    Bundle data = new Bundle();
                    data.putString(Constants.BundleKey.LABEL, tab.getCode());
                    data.putString(Constants.BundleKey.URL, tab.getUrl());
                    fragment.setArguments(data);

                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                mTabFragment.put(position, fragment);
            }
            if (fragment != null) {
                mCurSelectedTabId = position;
                mIndexPagerPosition = position;
                switchFragment(fragment);
                setFragmentVisible(fragment);
                checkNetErrorLayoutShow();
            }
        }
    }

    private void switchFragment(Fragment next) {
        if (next == null) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();

        //next fragment是否已经加入到activity 中
        if (!next.isAdded()) {
            // 隐藏当前的fragment，add下一个到Activity中
            if (mLastFragment != null) {
                transaction.hide(mLastFragment).add(R.id.vp_container, next);
            } else {
                transaction.add(R.id.vp_container, next);
            }
        } else {
            // 隐藏last fragment，显示next
            if (mLastFragment != null) {
                transaction.hide(mLastFragment).show(next);
            } else {
                transaction.show(next);
            }
        }
        mLastFragment = next;
        transaction.commitAllowingStateLoss();
    }

    private void setFragmentVisible(Fragment curFragment) {
        curFragment.setUserVisibleHint(true);
        if (mTabFragment.size() > 1) {
            for (int i = 0, len = mTabFragment.size(); i < len; i++) {
                Fragment fragment = mTabFragment.valueAt(i);
                if (fragment != curFragment) {
                    fragment.setUserVisibleHint(false);
                }
            }
        }
    }

    @Override
    public void selectPager(int position) {
        rgMainNav.check(tabIds[position]);
    }

    @Override
    public void showNotice(MainTab tab, int count) {

    }

    /**
     * 强制选择指定页
     *
     * @param position
     */
    private void selectPagerForce(int position) {
        if (rgMainNav.getCheckedRadioButtonId() == tabIds[position] && mOnCheckedChangeListener != null) {
            mOnCheckedChangeListener.onCheckedChanged(rgMainNav, rgMainNav.getCheckedRadioButtonId());
        } else {
            selectPager(position);
        }
    }

    @Override
    public void setTabsInfo(AppTabBean tab, Drawable drawable) {
        RadioButton rb = getTabItemById(tab.getCode());
        if (rb == null) {
            return;
        }
        rb.setText(tab.getTitle());

        int mTabIconSize = getResources().getDimensionPixelSize(R.dimen.dp_24);
        drawable.setBounds(0, 0, mTabIconSize, mTabIconSize);
        rb.setCompoundDrawables(null, drawable, null, null);
    }

    private RadioButton getTabItemById(String code) {
        if (MainTab.MAIN.getCode().equals(code)) {
            return mHomeRb;
        } else if (MainTab.CATE.getCode().equals(code)) {
            return mCateRb;
        } else if (MainTab.VIP.getCode().equals(code)) {
            return mVipRb;
        } else if (MainTab.ME.getCode().equals(code)) {
            return mMeRb;
        } else if (MainTab.CERT.getCode().equals(code)){
            return mCertRb;
        }
        return null;
    }

    private boolean shouldShowLogin(int position) {
        if (position == MainTab.ME.ordinal()
                && !AccountManager.getInstance().isLogin()) {
            RouterHelper.toUrl(this, Constants.Route.LOGIN_URL);
            return true;
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccess(LoginSuccessEvent e) {
        //AccountManager.getInstance().updateAccount(AccountManager.NameKey.TOKEN, e.token);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogout(LogoutEvent event) {
        if (mPosition == MainTab.ME.getPosition()) {
            selectPager(MainTab.MAIN.getPosition());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShare(ShareAction action) {
        ShareProxy.share(this, action);
    }

    @Override
    protected void onNetworkAvailable(NetworkInfo ni) {
        super.onNetworkAvailable(ni);
        TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
            @Override
            public void run() {
                checkNetErrorLayoutShow();
            }
        });
    }


    @Override
    protected void onNetworkUnavailable() {
        super.onNetworkUnavailable();
        TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
            @Override
            public void run() {
                checkNetErrorLayoutShow();
            }
        });
    }

    private void checkNetErrorLayoutShow() {
        llNetError.setVisibility(!isNetworkAvailable()
                && MainTab.values()[mIndexPagerPosition] != MainTab.ME ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onBackTransition() {
        overridePendingTransition(0, R.anim.activity_alpha_scale_out);
    }

    @Override
    protected void onDestroy() {
        if (mTabFragment.size() > 0) {
            for (int i = 0, len = mTabFragment.size(); i < len; i++) {
                Fragment fragment = mTabFragment.valueAt(i);
                fragment.onDestroy();
            }
        }
        mTabFragment.clear();

        mPresenter.onDestroy();
        mPresenter = null;

        TaskExecutor.shutdown();
        AnalyManager.getInstance().onXRKAnalyExit();

        ConfigManager.getInstance().hasMainActivityStarted(false);
        ConfigManager.getInstance().destroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (ExitUtil.exitForDoubleClick(this)) {
            AppManager.getInstance().AppExit();
        }
    }

    @Override
    public void onClick(View v) {
        if (PreventContinuousClickUtil.isContinuousClick()) {
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        showTabFragment(mPosition);
        checkNetErrorLayoutShow();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRoute2CustomerServiceEvent(Route2CustomerService event) {
        String title = "在线客服";
        /**
         * 设置访客来源，标识访客是从哪个页面发起咨询的，用于客服了解用户是从什么页面进入。
         * 三个参数分别为：来源页面的url，来源页面标题，来源页面额外信息（保留字段，暂时无用）。
         * 设置来源后，在客服会话界面的"用户资料"栏的页面项，可以看到这里设置的值。
         */
        ConsultSource source = new ConsultSource("", title, "custom information string");
        /**
         * 请注意： 调用该接口前，应先检查Unicorn.isServiceAvailable()，
         * 如果返回为false，该接口不会有任何动作
         *
         * @param context 上下文
         * @param title   聊天窗口的标题
         * @param source  咨询的发起来源，包括发起咨询的url，title，描述信息等
         */
        YSFUserInfo info = new YSFUserInfo();
        info.userId = AccountManager.getInstance().getAccount().uuid;
        Unicorn.setUserInfo(info);
        Unicorn.openServiceActivity(this, title, source);
    }

}